//
//  MBStartLiveController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/23.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBStartLiveController.h"
#import "MBLiveMainController.h"
#import "MBQiNiuUpTokenModel.h"
#import "MBOpenLiveModel.h"

@interface MBStartLiveController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UIImage *selectImage;
@property (nonatomic, strong) MBQiNiuUpTokenModel *upTokenModel;
@property (nonatomic, strong) MBOpenLiveModel *openLiveModel;


@end

@implementation MBStartLiveController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [self getQiniuUpToken];
}

/**
 获取七牛Token
 */
-(void)getQiniuUpToken {
    NSDictionary *param = @{
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        weakself.upTokenModel = [MBQiNiuUpTokenModel mj_objectWithKeyValues:AJson];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*上传图片 --> 七牛云*/
-(void)uploadImageWith:(NSString *)qiNiuToken {
    MB_WeakSelf(self);
    QNUploadManager *manager = [[QNUploadManager alloc]init];
    NSData *data = UIImageJPEGRepresentation(self.selectImage, 0.7);
    NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
    NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",filter([MBUserModel sharedMBUserModel].userInfo.userId),@"-",timeKey,@".jpg"];
    [manager putData:data key:imageName token:qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.statusCode == 200) {

    NSString *imageURL = [NSString stringWithFormat:@"%@",resp[@"key"]];
    [weakself openLiveWithCoverURL:imageURL];
//    [weakself.selecPictureButton sd_setBackgroundImageWithURL:imageURL forState:UIControlStateNormal];
            
        }
    } option:nil];
}

/*开启直播*/
-(void)openLiveWithCoverURL:(NSString *)imageURL {
    NSDictionary *param = @{
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"coverUrl":imageURL,
                            @"liveTitle":self.topTitleField.text,
                            @"wide":@(self.selectImage.size.width),
                            @"high":@(self.selectImage.size.height),
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_open setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        weakself.openLiveModel = [MBOpenLiveModel mj_objectWithKeyValues:AJson];
        MBLiveMainController *vc = [[MBLiveMainController alloc]init];
        vc.rtmpString = weakself.openLiveModel.pushUrl;
        vc.liveID = weakself.openLiveModel.liveId;
        vc.streamID = weakself.openLiveModel.streamId;
//        [[TIMGroupManager sharedInstance] joinGroup:weakself.openLiveModel.streamId msg:@"iOS" succ:^(){
//            [weakself.navigationController pushViewController:vc animated:YES];
//
//        }fail:^(int code, NSString * err) {
//            NSLog(@"code=%d, err=%@", code, err);
//        }];
        //创建群组
//        [[TIMGroupManager sharedInstance] createPrivateGroup:members groupName:@"GroupName" succ:^(NSString * group) {
//            NSLog(@"create group succ, sid=%@", group);
//        } fail:^(int code, NSString* err) {
//            NSLog(@"failed code: %d %@", code, err);
//        }];
        [[TIMGroupManager sharedInstance] createGroup:@"ChatRoom" groupId:weakself.openLiveModel.streamId groupName:self.openLiveModel.streamId succ:^(NSString *groupId) {
            
            [weakself.navigationController pushViewController:vc animated:YES];
            
        } fail:^(int code, NSString *msg) {
            
        }];

        /*调试使用*/
        [[NSUserDefaults standardUserDefaults]setObject:weakself.openLiveModel.liveId forKey:LocalLiveId];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}


-(void)createUI {
    self.view.backgroundColor = Color_White;
    self.topTitleLabel.textColor = Color_333333;
    self.topTitleLabel.font = kFont(16);
    self.topTitleField.font = kFont(16);
    self.topTitleField.placeholderFont = kFont(16);
    self.topLine.backgroundColor = Color_Line;
    self.liveCoverLabel.textColor = Color_333333;
    self.liveCoverLabel.font = kFont(16);
//    self.startLiveButton.layer.borderColor = Color_Line.CGColor;
//    self.startLiveButton.layer.borderWidth = 0.5;
    self.bottomContentView.backgroundColor = Color_F5F5F5;
    
    self.startLiveButton.layer.cornerRadius = 20.f;
    self.startLiveButton.layer.masksToBounds = YES;
    [self.startLiveButton setBackgroundColor:Color_FF8000];
    self.startLiveButton.titleLabel.font = kFont(16);
    [self.startLiveButton setTitleColor:Color_White forState:UIControlStateNormal];    
}
-(void)createCustomNav {
    self.navigationItem.title = @"发起直播";
}
- (IBAction)selectPictureButtonClick:(UIButton *)sender {
    MB_WeakSelf(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photographAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself takePhoto];
    }];
    UIAlertAction *selectPictureAction = [UIAlertAction actionWithTitle:@"从图库中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself pushTZImagePickerController];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:photographAction];
    [alert addAction:selectPictureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)startLiveButtonClick:(UIButton *)sender {
    if (self.topTitleField.text.length == 0) {
        [self.view makeToast:@"请先选择标题" duration:2.0f position:CSToastPositionBottom];
        return;
    }
    if (self.selectImage == nil) {
        [self.view makeToast:@"请先选择封面" duration:2.0f position:CSToastPositionBottom];
        return;
    }
    if (self.upTokenModel.upToken) {
        [self uploadImageWith:self.upTokenModel.upToken];
    }
}
/*关闭直播*/
- (IBAction)endLiveButtonClick:(UIButton *)sender {
//    if(self.openLiveModel.liveId == nil){
//        [self.view makeToast:@"还未开始直播" duration:2.0f position:CSToastPositionBottom];
//        return;
//    }
    NSDictionary *param = @{
                            //                            @"liveId":self.liveID,
                            @"liveId":[[NSUserDefaults standardUserDefaults]objectForKey:LocalLiveId],
                            @"liveUserId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_close setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/*拍照*/
-(void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            NSMutableArray *mediaTypes = [NSMutableArray array];
            [mediaTypes addObject:(NSString *)kUTTypeImage];
            if (mediaTypes.count) {
                _imagePickerVc.mediaTypes = mediaTypes;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

-(void)pushTZImagePickerController{
    MB_WeakSelf(self);
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        UIImage *image = photos.firstObject;
        UIImage *resultImage = [UIImage compressImage:image toKBByte:300];
        weakself.selectImage = resultImage;
        [weakself.selecPictureButton setImage:resultImage forState:UIControlStateNormal];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *resultImage = [UIImage compressImage:image toKBByte:300];
    self.selectImage = resultImage;
   [self.selecPictureButton setImage:resultImage forState:UIControlStateNormal];
}

#pragma mark - getter and setter
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}


@end
